package top.linyuxb.lycloud.common.constant;

import lombok.Getter;
import top.linyuxb.lycloud.common.dto.LyRpcServerDto;
import top.linyuxb.lycloud.common.utils.LyRpcRibbonUtil;

import java.util.Objects;
import java.util.stream.Stream;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/6/7 11:31
 * @Desc: 负载均衡器类型
 */
@Getter
public enum LyRpcRobinType {
    ROUND_ROBIN("轮询", "roundRobin") {
        @Override
        public LyRpcServerDto getServer(String app, String env, String clientIP) {
            return LyRpcRibbonUtil.roundRobin(app, env);
        }
    },
    WEIGHT_ROBIN("加权轮询", "weightRobin") {
        @Override
        public LyRpcServerDto getServer(String app, String env, String clientIP) {
            return LyRpcRibbonUtil.weightRobin(app, env);
        }
    },
    RANDOM("随机", "random") {
        @Override
        public LyRpcServerDto getServer(String app, String env, String clientIP) {
            return LyRpcRibbonUtil.random(app, env);
        }
    },
    WEIGHT_RANDOM("加权随机", "weightRandom") {
        @Override
        public LyRpcServerDto getServer(String app, String env, String clientIP) {
            return LyRpcRibbonUtil.weightRandom(app, env);
        }
    },
    IP_HASH("ip哈希", "ipHash") {
        @Override
        public LyRpcServerDto getServer(String app, String env, String clientIP) {
            return LyRpcRibbonUtil.ipHash(app, env, clientIP);
        }
    },

    ;
    /**
     * 类型
     */
    private final String desc;
    private final String type;

    LyRpcRobinType(String desc, String type) {
        this.desc = desc;
        this.type = type;
    }

    /**
     * 获取类型
     *
     * @param type
     * @return
     */
    public static LyRpcRobinType getRobinByType(String type) {
        return Stream.of(LyRpcRobinType.values())
                .filter(lyRpcRobinType -> Objects.equals(lyRpcRobinType.getType(), type))
                .findAny()
                .orElseGet(() -> ROUND_ROBIN);
    }

    /**
     * 获取服务
     *
     * @param app
     * @param env
     * @param clientIP
     * @return
     */
    public abstract LyRpcServerDto getServer(String app, String env, String clientIP);
}
